"""
附加分审查模块API视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q

from .models import ExtraReview
from .serializers import ExtraReviewSerializer, ExtraReviewListSerializer
from certificate.models import Certificate


class ExtraReviewViewSet(viewsets.ModelViewSet):
    """
    附加分审查ViewSet
    
    提供附加分审查的操作:
        - list: 获取审查列表（根据角色显示）
        - retrieve: 获取审查详情
        - create: 提交审查申请（学生）
        - update: 更新审查信息
        - destroy: 删除审查记录
        - approve: 审核通过
        - reject: 审核拒绝
    """
    queryset = ExtraReview.objects.all().select_related('student', 'student__profile')
    serializer_class = ExtraReviewSerializer
    permission_classes = [IsAuthenticated]
    
    def get_serializer_class(self):
        """根据不同的action返回不同的序列化器"""
        if self.action == 'list':
            return ExtraReviewListSerializer
        return ExtraReviewSerializer
    
    def get_queryset(self):
        """
        根据用户角色返回不同的查询集
        
        - 学生: 只能看到自己的申请
        - 班委: 可以看到本班待审核的申请
        - 辅导员: 可以看到本专业待审核的申请
        - 学工办/管理员: 可以看到所有申请
        """
        user = self.request.user
        queryset = ExtraReview.objects.all().select_related('student', 'student__profile')
        
        # 超级管理员或学工办可以看到所有记录
        if user.is_superuser or user.is_staff:
            pass
        elif hasattr(user, 'profile'):
            # 根据职位判断权限
            position = user.profile.position or ''
            if '辅导员' in position:
                # 辅导员可以看到本专业的申请
                major = user.profile.major
                queryset = queryset.filter(student__profile__major=major)
            elif '班委' in position:
                # 班委可以看到本班的申请
                class_name = user.profile.class_name
                queryset = queryset.filter(classes=class_name)
            else:
                # 普通学生只能看到自己的申请
                queryset = queryset.filter(student=user)
        else:
            # 默认只能看到自己的
            queryset = queryset.filter(student=user)
        
        # 学生筛选
        student_id = self.request.query_params.get('student', None)
        if student_id:
            queryset = queryset.filter(student_id=student_id)
        
        # 年份筛选
        time = self.request.query_params.get('time', None)
        if time:
            queryset = queryset.filter(time=time)
        
        # 状态筛选
        status_filter = self.request.query_params.get('status', None)
        if status_filter == 'pending':
            # 待审核（任意一级未通过）
            queryset = queryset.filter(
                Q(first_efficient=False) | 
                Q(second_efficient=False) | 
                Q(third_efficient=False)
            )
        elif status_filter == 'approved':
            # 已通过（三级全部通过）
            queryset = queryset.filter(
                first_efficient=True,
                second_efficient=True,
                third_efficient=True
            )
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """
        提交附加分审查申请
        
        学生上传证书并提交审核
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 保存数据，序列化器会自动关联当前用户
        instance = serializer.save()
        
        # 重新序列化以包含完整的关联数据
        response_serializer = self.get_serializer(instance)
        
        return Response({
            'code': 201,
            'message': '提交成功，等待审核',
            'data': response_serializer.data
        }, status=status.HTTP_201_CREATED)
    
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        """
        审核通过
        
        参数:
            - level: 审核级别 (first/second/third)
            - remarks: 审核备注
        """
        instance = self.get_object()
        level = request.data.get('level')
        remarks = request.data.get('remarks', '')
        
        # 检查是否已经审核过
        if level == 'first' and instance.first_efficient:
            return Response({
                'code': 400,
                'message': '该级别已审核通过，无法重复审核'
            }, status=status.HTTP_400_BAD_REQUEST)
        elif level == 'second' and instance.second_efficient:
            return Response({
                'code': 400,
                'message': '该级别已审核通过，无法重复审核'
            }, status=status.HTTP_400_BAD_REQUEST)
        elif level == 'third' and instance.third_efficient:
            return Response({
                'code': 400,
                'message': '该级别已审核通过，无法重复审核'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查权限并设置对应的审核状态
        user = request.user
        if level == 'first':
            # 学工办审核
            if not (user.is_staff or user.is_superuser):
                return Response({
                    'code': 403,
                    'message': '权限不足，仅学工办可进行终审'
                }, status=status.HTTP_403_FORBIDDEN)
            instance.first_efficient = True
        elif level == 'second':
            # 辅导员审核
            position = getattr(user.profile, 'position', '') if hasattr(user, 'profile') else ''
            if not ('辅导员' in position or user.is_staff or user.is_superuser):
                return Response({
                    'code': 403,
                    'message': '权限不足，仅辅导员可进行复审'
                }, status=status.HTTP_403_FORBIDDEN)
            instance.second_efficient = True
        elif level == 'third':
            # 班委审核
            position = getattr(user.profile, 'position', '') if hasattr(user, 'profile') else ''
            if not ('班委' in position or user.is_staff or user.is_superuser):
                return Response({
                    'code': 403,
                    'message': '权限不足，仅班委可进行初审'
                }, status=status.HTTP_403_FORBIDDEN)
            instance.third_efficient = True
        else:
            return Response({
                'code': 400,
                'message': '无效的审核级别'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        instance.auditor = f"{instance.auditor or ''}{user.username}({level}){': ' + remarks if remarks else ''};"
        instance.save()
        
        return Response({
            'code': 200,
            'message': '审核通过'
        })
    
    @action(detail=True, methods=['post'])
    def reject(self, request, pk=None):
        """
        审核拒绝
        
        参数:
            - level: 审核级别 (first/second/third)
            - reason: 拒绝原因
        """
        instance = self.get_object()
        level = request.data.get('level')
        reason = request.data.get('reason', '未通过审核')
        
        # 检查权限
        user = request.user
        if level == 'first' and not (user.is_staff or user.is_superuser):
            return Response({
                'code': 403,
                'message': '权限不足'
            }, status=status.HTTP_403_FORBIDDEN)
        
        # 记录拒绝信息
        instance.auditor = f"{instance.auditor or ''}{user.username}(拒绝-{level}): {reason};"
        instance.save()
        
        return Response({
            'code': 200,
            'message': '已拒绝该申请',
            'data': {
                'reason': reason
            }
        })
    
    @action(detail=False, methods=['post'])
    def sync_grades(self, request):
        """
        批量同步分数
        
        根据证书字典更新所有附加分记录的分数
        权限：仅管理员可执行
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可执行此操作'
            }, status=status.HTTP_403_FORBIDDEN)
        
        updated_count = 0
        reviews = ExtraReview.objects.all()
        
        for review in reviews:
            try:
                certificate = Certificate.objects.filter(
                    sort=review.sort,
                    name=review.name,
                    ranks=review.ranks,
                    classes=review.levels
                ).first()
                
                if certificate:
                    review.grade = certificate.grade
                    review.save(update_fields=['grade'])
                    updated_count += 1
            except Exception:
                continue
        
        return Response({
            'code': 200,
            'message': f'成功同步 {updated_count} 条记录的分数',
            'data': {
                'updated_count': updated_count,
                'total_count': reviews.count()
            }
        })
